<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
      <el-form-item label="商品名称" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="商品分类" prop="categoryId">
        <el-select
          v-model="queryParams.categoryId"
          filterable
          clearable
          placeholder="请选择"
        >
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.categoryName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >查询</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="openDrawer"
          >新建商品</el-button
        >
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="goodsList">
      <!-- <el-table-column label="ID" prop="id" width="120" /> -->
      <el-table-column label="商品名称" prop="goodsName" />
      <el-table-column label="商品分类" prop="categoryId">
        <template slot-scope="scope">
          {{ selectCategoryIdLabel(scope.row.categoryId) }}
        </template>
      </el-table-column>
      <el-table-column label="商品头图">
        <template slot-scope="scope">
          <el-image
            style="width: 40px; height: 40px"
            :src="scope.row.goodsPhoto"
            fit="cover"
            :preview-src-list="[scope.row.goodsPhoto]"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="商品编码" prop="goodsCode" />
      <el-table-column label="更新人" prop="updateByName">
        <template slot-scope="scope">
          {{ formatTableValue(scope.row.updateByName) }}
        </template>
      </el-table-column>
      <el-table-column label="更新时间" prop="updateTime" />
      <el-table-column label="状态" prop="roleSort">
        <template slot-scope="scope">
          {{ scope.row.status == 1 ? "已上架" : "已下架" }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <div class="operate-box">
            <el-button type="text" @click="openDrawer('edit', scope.row)"
              >编辑</el-button
            >
            |
            <el-button type="text" @click="handleUnmounte(scope.row)">{{
              scope.row.status == 0 ? "上架" : "下架"
            }}</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      :title="drawerTitle"
      :visible.sync="drawerVisible"
      width="900px"
      append-to-body
      custom-class="custom-dialog"
      @close="closeDialog" :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="120px">
        <el-form-item label="商品名称：" prop="goodsName">
          <el-input
            v-model="form.goodsName"
            placeholder="请输入商品名称"
            maxlength="50"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品副标题：" prop="goodsSubtitle">
          <el-input
            v-model="form.goodsSubtitle"
            placeholder="请输入商品副标题"
            maxlength="100"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品标签：">
          <div class="flex flex-col">
            <section class="flex">
              <el-input
                v-model="formTag"
                placeholder="请输入商品标签，限5个字"
                maxlength="5"
              ></el-input>
              <el-button
                type="primary"
                class="add-btn"
                @click="handleInputConfirm"
                >添加</el-button
              >
            </section>
            <section>
              <el-tag
                v-for="(item, index) in goodsLabelList"
                :key="index"
                closable
                style="margin-right: 10px"
                @close="handleCloseTag(item)"
              >
                {{ item }}
              </el-tag>
            </section>
          </div>
        </el-form-item>
        <el-form-item label="商品规格：">
          <el-form
            ref="categoryFormRef"
            :model="specification"
            :rules="specRules"
            inline
            class="shdhfs"
          >
            <el-form-item prop="goodsSpecName">
              <el-input
                v-model="specification.goodsSpecName"
                placeholder="请输入商品规格名称"
                maxlength="20"
              ></el-input>
            </el-form-item>
            <el-form-item prop="goodsNum">
              <el-input
                v-model="specification.goodsNum"
                placeholder="对应商品数量"
                maxlength="5"
              ></el-input>
            </el-form-item>
            <el-form-item prop="sort">
              <el-input
                v-model="specification.sort"
                placeholder="请输入排序值"
                maxlength="5"
              ></el-input>
            </el-form-item>
            <el-form-item prop="retailPrice">
              <el-input
                v-model="specification.retailPrice"
                placeholder="请输入零售价格"
                maxlength="10"
              ></el-input>
            </el-form-item>
            <el-form-item prop="memberMoney">
              <el-input
                v-model="specification.memberMoney"
                placeholder="请输入会员价格"
                maxlength="10"
              ></el-input>
            </el-form-item>
            <el-form-item prop="commission">
              <section class="flex">
                <el-input
                  v-model="specification.commission"
                  placeholder="请输入分佣比例"
                  maxlength="10"
                ></el-input>
                <el-button
                  type="primary"
                  class="add-btn"
                  @click="addSpecification('categoryFormRef')"
                  >添加</el-button
                >
              </section>
            </el-form-item>
          </el-form>

          <el-table :data="formSpecList" class="spec-table">
            <el-table-column
              label="规格名称"
              prop="goodsSpecName"
              width="150px"
            />
            <el-table-column label="商品数量" prop="goodsNum" align="center" />
            <el-table-column label="零售价" prop="retailPrice" align="center" />
            <el-table-column label="会员价" prop="memberMoney" align="center" />
            <el-table-column
              label="分佣比例(%)"
              prop="commission"
              align="center"
            />
            <el-table-column label="排序值" prop="sort" align="center" />
            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <div class="operate-box">
                  <el-button type="text" @click="handleDeleteSpec(scope.$index)"
                    >删除</el-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <div class="form-row">
          <el-form-item label="商品分类：" prop="categoryId">
            <el-select
              v-model="form.categoryId"
              placeholder="请选择"
              class="w-full"
            >
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.categoryName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品编码：" prop="goodsCode">
            <el-input
              v-number-input
              v-model="form.goodsCode"
              placeholder="限输入数字"
              maxlength="15"
            ></el-input>
          </el-form-item>
        </div>
        <el-form-item label="排序值：" prop="sort">
          <el-input
            v-number-input
            v-model="form.sort"
            placeholder="限输入数字"
            maxlength="5"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品头图：" prop="goodsPhoto">
          <el-input v-model="form.goodsPhoto" v-show="false" />
          <div class="flex flex-col">
            <ImageUpload
              :value="form.goodsPhoto"
              :limit="1"
              @input="handleFileSuccess"
            />
          </div>
        </el-form-item>
        <el-form-item label="商品描述：">
          <editor v-model="form.goodsDescribe" :min-height="192" />
        </el-form-item>
        <el-form-item>
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >确定</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCategoryListAPI,
  getGoodsListAPI,
  updateGoods,
  addGoodsAPI,
} from "@/api/system/product";

export default {
  data() {
    const validateNumber = (rule, value, callback) => {
      if (!/^\d*\.?\d{0,2}$/.test(value)) {
        callback(new Error("请输入数字，最多2位小数"));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      ids: [],
      goodsList: [],
      total: 1,
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        goodsName: undefined,
        categoryId: undefined,
      },
      options: [],
      drawerVisible: false,
      drawerTitle: "",
      form: {
        goodsName: "",
        goodsSubtitle: "",
        goodsCode: "",
        sort: "",
      },
      goodsLabelList: [],
      rules: {
        goodsName: [
          {
            required: true,
            message: "商品名称必填，限输入50个字",
            trigger: "blur",
          },
        ],
        goodsSubtitle: [
          {
            required: true,
            message: "商品副标题必填，限输入100个字",
            trigger: "blur",
          },
        ],
        categoryId: [
          {
            required: true,
            message: "商品分类必选",
            trigger: "change",
          },
        ],
        goodsCode: [
          {
            required: true,
            message: "商品编码必填，限输入15个字符",
            trigger: "blur",
          },
        ],
        sort: [
          {
            required: true,
            message: "排序值必填，限输入5个字符",
            trigger: "blur",
          },
        ],
        goodsDescribe: [
          {
            required: true,
            message: "商品描述必填，限输入500个字",
            trigger: "blur",
          },
        ],
        goodsPhoto: [
          {
            required: true,
            message: "商品头图必填",
            trigger: "change",
          },
        ],
      },
      formSpecList: [],
      specification: {
        goodsId: "",
        goodsSpecName: "",
        goodsNum: "",
        sort: "",
        retailPrice: "",
        memberMoney: "",
        commission: "",
      },
      categoryForm: {
        categoryName: "",
        sort: "",
      },
      specRules: {
        goodsSpecName: [
          {
            required: true,
            message: "规格名称必填，限输入20个字",
            trigger: "blur",
          },
        ],
        goodsNum: [
          { validator: validateNumber, trigger: "blur" },
          {
            required: true,
            message: "对应商品数量必填，限输入5个字符",
            trigger: "blur",
          },
        ],
        sort: [
          { validator: validateNumber, trigger: "blur" },
          {
            required: true,
            message: "排序值必填，限输入5个字符",
            trigger: "blur",
          },
        ],
        retailPrice: [
          { validator: validateNumber, trigger: "blur" },
          {
            required: true,
            message: "零售价必填，限输入10个字符",
            trigger: "blur",
          },
        ],
        memberMoney: [
          { validator: validateNumber, trigger: "blur" },
          {
            required: true,
            message: "会员价必填，限输入10个字符",
            trigger: "blur",
          },
        ],
        commission: [
          { validator: validateNumber, trigger: "blur" },
          {
            required: true,
            message: "分佣比例必填，限输入10个字符",
            trigger: "blur",
          },
        ],
      },
      formTag: "",
    };
  },
  computed: {
    selectCategoryIdLabel() {
      return (id) => {
        const item = this.options.find((item) => item.id === id);
        return item ? item.categoryName : "";
      };
    },
  },
  created() {
    this.getCateList();
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      getGoodsListAPI(this.queryParams).then((response) => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 商品分类
    getCateList() {
      getCategoryListAPI({
        pageNum: 1,
        pageSize: 1000000,
      }).then((response) => {
        this.options = response.rows;
      });
    },
    // 商品规格：添加
    addSpecification(formName) {
      this.$refs[formName].validate(async (valid, errorObj) => {
        if (valid) {
          this.formSpecList.push({ ...this.specification });
          this.specification = {
            goodsSpecName: "",
            goodsNum: "",
            sort: "",
            retailPrice: "",
            memberMoney: "",
            commission: "",
          };
        }
      });
    },
    // 商品规格：删除
    handleDeleteSpec(index) {
      this.formSpecList.splice(index, 1);
    },
    // 文件上传成功处理
    handleFileSuccess(response) {
      this.form.goodsPhoto = response;
    },
    // 标签添加
    handleInputConfirm() {
      if (this.formTag) {
        this.goodsLabelList.push(this.formTag);
        this.formTag = "";
      }
    },
    handleCloseTag(tag) {
      this.goodsLabelList.splice(this.goodsLabelList.indexOf(tag), 1);
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    handleUnmounte(row) {
      let title = "";
      if (row.status == 0) {
        title = "上架该商品?";
      } else {
        title = "下架后该商品前台不可见，是否确认下架?";
      }

      this.$confirm(title, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          updateGoods({
            id: row.id,
            status: row.status == 0 ? 1 : 0,
          }).then((response) => {
            if (response.code === 200) {
              this.$message({
                type: "success",
                message: "操作成功!",
              });
              this.getList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: row.status == 0 ? "已取消上架" : "已取消下架",
          });
        });
    },
    openDrawer(type, row) {
      this.drawerTitle = type === "edit" ? "编辑商品" : "新建商品";
      this.drawerVisible = true;

      if (type === "edit") {
        this.form = { ...row };
        this.formSpecList = JSON.parse(row.goodsSpec);
        this.goodsLabelList = this.form.goodsLabel
          .slice(1, -1)
          .split(",")
          .map((item) => item.trim());
      } else {
        this.form = {
          goodsName: "",
          goodsSubtitle: "",
          goodsCode: "",
          sort: "",
          categoryId: "",
          goodsDescribe: "",
          goodsPhoto: "",
          goodsSpec: "",
          goodsLabel: "",
          status: 1,
        };
        this.formSpecList = [];
        this.goodsLabelList = [];
      }
    },
    closeDialog() {
      this.drawerVisible = false;
      this.resetForm("ruleForm");
      this.resetForm("categoryFormRef");
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    submitForm(formName) {
      this.$refs[formName].validate(async (valid, errorObj) => {
        if (valid) {
          if (this.goodsLabelList.length == 0) {
            this.$message({
              type: "error",
              message: "请添加商品标签",
            });
            return;
          }
          if (this.formSpecList.length == 0) {
            this.$message({
              type: "error",
              message: "请添加商品规格",
            });
            return;
          }
          if (this.form.goodsPhoto == "") {
            this.$message({
              type: "error",
              message: "请添加商品头图",
            });
            return;
          }
          let p = { ...this.form };
          p.goodsSpecList = this.formSpecList;
          p.goodsLabelList = this.goodsLabelList;
          let res = null;
          if (this.form.id != undefined) {
            res = await updateGoods(p);
            if (res.code == 200) {
              this.getList();
              this.$modal.msgSuccess("修改成功");
              this.drawerVisible = false;
            }
          } else {
            res = await addGoodsAPI(p);
            if (res.code == 200) {
              this.getList();
              this.$modal.msgSuccess("新增成功");
              this.drawerVisible = false;
            }
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scopd>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #8c939d;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.custom-drawer .el-drawer__body {
  padding: 0 40px;
}

.specification-box {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
}

.add-btn {
  margin-left: 4px;
}

.form-row {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24px;
}

.spec-table {
  margin-top: 20px;
}

.shdhfs {
  .el-form-item {
    margin-bottom: 20px;
  }
}
</style>
